package com.hle;

public class CoinChange {

	public static void main(String[] args) {
//		System.out.println(coins1(41));	
//		System.out.println(coins2(41));	
//		System.out.println(coins3(41));		
//		System.out.println(coins4(41));	
		System.out.println(coin5(41, new int[] {1,5,20,25}));
	}
	
	static int coin5(int amount, int[] coins) {
		int[] dp = new int[amount + 1];
		if (amount < 0 || coins == null || coins.length == 0) return -1;
		for (int i = 1; i < dp.length; i++) {
			int min = Integer.MAX_VALUE;
			for (int face : coins) {
				if (i < face) continue;
				int v =  dp[i - face];
				if (v < 0 || v >= min) continue;
				min = v;
			}
			if (min == Integer.MAX_VALUE) {
				dp[i] = -1;
			}else {
				dp[i] = min + 1;
			}
		}
		return dp[amount];
	}	
	
	static int coins4(int n) {
		int[] dp = new int[n + 1];
		int[] face = new int[dp.length];
		for (int i = 1; i < n + 1; i++) {
			int min = dp[i - 1];
			face[i] = 1;
			
			if (i >= 5 && dp[i - 5] < min) {
				min = dp[i - 5];
				face[i] = 5;
			}
			if (i >= 20 && dp[i - 20] < min) {
				min = dp[i - 20];
				face[i] = 20;
			}
			if (i >= 25 && dp[i - 25] < min) {
				min = dp[i - 25];
				face[25] = 25;
			}
			dp[i] = min + 1;
		}
		print(face, n);
		return dp[n];
	}
	
	static void print(int[] face, int n) {
		System.out.println("--------");
		while (n > 0) {
			System.out.println(face[n] + " ");
			n -= face[n];
		}
		System.out.println("--------");
	}
	
	static int coins3(int n) {
		int[] dp = new int[n + 1];
		for (int i = 1; i < n + 1; i++) {
			int min = dp[i - 1];
			if (i >= 5) min = Math.min(dp[i - 5], min);
			if (i >= 20) min = Math.min(dp[i - 20], min);
			if (i >= 25) min = Math.min(dp[i - 25], min);
			dp[i] = min + 1;
		}
		return dp[n];
	}
	
	static int coins2(int n) {
		int[] dp = new int[n + 1];
		dp[1] = dp[5] = dp[20] = dp[25] = 1;
		return coins2(n, dp);
	}
	
	static int coins2(int n, int[] dp) {
		if (n < 1 ) return Integer.MAX_VALUE;
		if (dp[n] == 0) {
			int min1 = Math.min(coins2(n - 25,dp), coins2(n - 20,dp));
			int min2 = Math.min(coins2(n - 5,dp),coins2(n - 1,dp));
			return Math.min(min1, min2) + 1;
		}
		return dp[n];
	}
	
	static int coins1(int n) {
		if (n < 1) return Integer.MAX_VALUE;
		if (n == 25 || n == 20 || n == 5 || n == 1) return 1;
		int min1 = Math.min(coins1(n - 25), coins1(n - 20));
		int min2 = Math.min(coins1(n - 5), coins1(n - 1));
		return Math.min(min1, min2) + 1;
	}
}
